package com.example.cart.web;

import com.example.cart.model.Car;
import com.example.cart.model.User;
import com.example.cart.service.UserService;
import com.example.cart.utils.MyResult;
import com.example.cart.utils.MyUtils;
import com.example.cart.utils.TokenProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    // 登录
    @PostMapping(value = "/login")
    public Map<String, Object> login(@RequestBody User user) {
        // 登录
        User userObj = userService.login(user);
        if(userObj == null) {   // 账号或密码错误
            // 返回结果对象
            return MyResult.getResultMap(420, "账号或密码错误");
        } else {    // 账号密码正确
            // 创建token
            String token = TokenProcessor.getInstance().makeToken();
            // 保存到Redis
            userService.saveUser(token, userObj);
            // 返回结果对象
            return MyResult.getResultMap(200, "登录成功",
                    new HashMap<String, String>(){{ put("token", token); }});
        }
    }

    //注册
    @RequestMapping(value = "/register")
    public Integer register(String username,String password){ return userService.register(username,password);}

    //修改密码
    @RequestMapping(value = "/alterpassword")
    public Integer alterPassword(Integer id,String username,String password,String role,String newpassword){
        User tempt = new User(username,password);
        tempt.setId(id);
        tempt.setRole(role);
        User user = userService.login(tempt);
        if(user == null)
            return 0;
        else{
            userService.setPassword(user.getId(),newpassword);
            return 1;
        }
    }
    //查寻所有用户
    @GetMapping(value="/searchAllUsers")
    public List<User> searchAllUsers(){ return userService.getAll();}

    @GetMapping(value = "/uuu")
    public Map<String,Object> searchCarsByPage(@RequestParam Map<String,Object> params){
        MyUtils.parsePageParams(params);
        int count = userService.getSearchCount(params); //获得总数
        List<User> users = userService.searchUsersByPage(params); //分页查询
        return MyResult.getListResultMap(0,"success",count,users);
    }

    //添加用户
    @PostMapping(value = "/addUser")
    public Integer addUser(@RequestBody User user){ return userService.add(user); }

    //删除用户
    @DeleteMapping(value = "deleteUser")
    public Integer deleteUser(@RequestBody User user){ return userService.delete(user); }

    //更改用户信息
    @RequestMapping(value = "/updateUser")
    public Integer updateUser(@RequestBody User user){ return userService.update(user); }
}